package server.handler;

import java.io.UnsupportedEncodingException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class ReadHandler extends AbstractSelectionKeyHandler {

    @Override
    public boolean preHandler(SelectionKey selectionKey) {
        return selectionKey.isReadable();
    }

    @Override
    public void handler(SelectionKey selectionKey) {
        try {
            // 清空缓存
            this.readBuffer.clear();
            // 获取当前通道对象
            SocketChannel channel = (SocketChannel) selectionKey.channel();
            // 将通道数据读取到缓存中
            int readLength = channel.read(readBuffer);
            // 无数据则关闭
            if (readLength == -1) {
                selectionKey.channel().close();
                selectionKey.cancel();
                return;
            }
            // 读取数据
            String message = readMessage();
            System.out.println("server read message = " + message);
            // 标记通道为写操作
            channel.register(this.selector, SelectionKey.OP_WRITE);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private String readMessage() throws UnsupportedEncodingException {
        // 重置buffer游标（游标默认不会自动重置）
        this.readBuffer.flip();
        // 创建有效字节数组
        byte[] bufferBytes = new byte[readBuffer.remaining()];
        // 读取buffer数据保存在字节数组中
        return new String(bufferBytes, StandardCharsets.UTF_8);
    }
}
